//
//  MSMapsView.m
//  MyMap
//
//  Created by xiangbo on 2018/10/12.
//  Copyright © 2018年 swinglife. All rights reserved.
//

#import "MSMapsView.h"
#import "MSAnnotationView.h"

@interface MSMapsView()<MKMapViewDelegate,CLLocationManagerDelegate>

@property (nonatomic, strong)CLGeocoder *geocoder;

@end

@implementation MSMapsView

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.mapView = [[MKMapView alloc] init];
        [self addSubview:self.mapView];
        [self setupMaps];
    }
    return self;
}

- (void)setupMaps{
    //设置MapView的委托为自己
    [self.mapView setDelegate:self];
    self.mapView.userTrackingMode = MKUserTrackingModeNone;
    self.mapView.zoomEnabled = YES;
    self.mapView.scrollEnabled = YES;
    self.mapView.rotateEnabled = YES;
    self.mapView.showsCompass = YES;
    self.mapView.showsScale = YES;
    self.mapView.showsUserLocation = YES;
    
    //标注自身位置
    [self.mapView setShowsUserLocation:YES];
    [self.mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    if ([MSLocationManager shareInstance].currentPlace) {
        MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([MSLocationManager shareInstance].currentPlace.location.coordinate, 5000, 5000);
        [self.mapView setRegion:region animated:YES];
    }
    
}
#pragma mark - 地图的代理方法
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    static NSString *ID = @"anno";
    if ([annotation isKindOfClass:MKUserLocation.class]) {
        MKPinAnnotationView *annoView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:ID];
        
        if (annoView == nil) {
            annoView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:ID];
            // 显示气泡
            annoView.canShowCallout = YES;
            // 设置绿色
            annoView.pinTintColor = [MKPinAnnotationView greenPinColor];
        }
        return annoView;
    }else if([annotation isKindOfClass:MKAnnotationView.class]){
        MKAnnotationView *annoView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"CustomAnnotation"];
        if (!annoView) {
            annoView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"CustomAnnotation"];
            annoView.canShowCallout = YES;
        }
        return annoView;
    }
    return nil;
    
}
- (void)gotoLocation:(CLLocation *)fromLocation to:(CLLocation *)toLocation{
    if (!toLocation) {
        return;
    }
    _WEAKSELF
    if (fromLocation) {
        [self.geocoder reverseGeocodeLocation:fromLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            if (placemarks.count > 0) {
                CLPlacemark *fromPlace = placemarks.firstObject;
                [weakSelf.geocoder reverseGeocodeLocation:toLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
                    if (placemarks.count > 0) {
                        CLPlacemark *toPlace = placemarks.firstObject;
                        [weakSelf addLineFrom:fromPlace to:toPlace];
                    }
                }];
                
            }
        }];
    }else if([MSLocationManager shareInstance].currentPlace){
        [self.geocoder reverseGeocodeLocation:toLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            if (placemarks.count > 0) {
                CLPlacemark *toPlace = placemarks.firstObject;
                [weakSelf addLineFrom:[MSLocationManager shareInstance].currentPlace to:toPlace];
            }
        }];
    }
    
}
#pragma mark - 规划路线
- (void)addLineFrom:(CLPlacemark *)from to:(CLPlacemark *)to {
    //1.在起始和结束位置上插入两个大头针
    NSArray *annotation = self.mapView.annotations;
    [self.mapView removeAnnotations:annotation];
    MSAnnotationView *oneAnnotation = [[MSAnnotationView alloc]init];
    oneAnnotation.title = from.name;
    oneAnnotation.coordinate = from.location.coordinate;
    MSAnnotationView *twoAnnotation = [[MSAnnotationView alloc]init];
    twoAnnotation.coordinate = to.location.coordinate;
    twoAnnotation.title = to.name;
    //添加在地图上
    [self.mapView addAnnotations:@[oneAnnotation, twoAnnotation]];
    [self.mapView showAnnotations:@[oneAnnotation, twoAnnotation] animated:YES];
    //2.开始路线请求
    MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
    //3.选择出行模式
    request.transportType = MKDirectionsTransportTypeWalking;
    //4.设置路线的起点
    MKPlacemark *sourcePlace = [[MKPlacemark alloc]initWithPlacemark:from];
    request.source = [[MKMapItem alloc] initWithPlacemark:sourcePlace];
    //5.设置路线的终点
    MKPlacemark *destinationPlace = [[MKPlacemark alloc]initWithPlacemark:to];
    request.destination = [[MKMapItem alloc]initWithPlacemark:destinationPlace];
    //6.根据请求对象获取路线对象
    MKDirections *direction = [[MKDirections alloc]initWithRequest:request];
    //7.计算路线(路线由一条条路段组成.而路段由一个个的轨迹点组成)
    [direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"总共有%lu条路线组成", response.routes.count);
        //填充轨迹点模型.
        for (MKRoute *route in response.routes) {
            [self.mapView addOverlay:route.polyline];
        }
    }];
}
#pragma mark - MKMapViewDelegate
//7.设置线路遮蔽物（红色线条）宽度，颜色:MKPolylineRenderer
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id <MKOverlay>)overlay{
    MKPolylineRenderer *ployline = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
    ployline.fillColor = [UIColor blueColor];
    ployline.strokeColor = [UIColor redColor];
    ployline.lineWidth = 3.0;
    return ployline;
}

//懒加载---给地理编码对象开空间
- (CLGeocoder *)geocoder {
    if (_geocoder == nil) {
        self.geocoder = [[CLGeocoder alloc]init];
    }
    return _geocoder;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
